package articleEvents

import (
	"context"
	"encoding/json"
	"github.com/IBM/sarama"
)

type Producer interface {
	ProduceReadEvent(ctx context.Context, evt ReadEvent) error
}
type InteractiveKafkaProducer struct {
	producer sarama.SyncProducer
}

func NewInteractiveKafkaProducer(pc sarama.SyncProducer) Producer {
	return &InteractiveKafkaProducer{producer: pc}
}

// ProduceReadEvent 有复杂的重试逻辑，就用装饰器
func (k *InteractiveKafkaProducer) ProduceReadEvent(ctx context.Context, evt ReadEvent) error {
	data, err := json.Marshal(evt)
	if err != nil {
		return err
	}
	_, _, err = k.producer.SendMessage(&sarama.ProducerMessage{
		Topic: evt.Topic(),
		Value: sarama.ByteEncoder(data),
	})
	return err
}

type ReadEvent struct {
	UUID string
	Aid  int64
	Uid  int64
}

func (ReadEvent) Topic() string {
	return "article_read"
}
